<?php
/**
 * XiteCode base object
 *
 * @copyright (c) 2006 A.Sleep <a.sleep@asleep.net> under the GNU GPL version 2
 * @author A.Sleep <a.sleep@asleep.net>
 * @package core
 * @access public
 */

class XiteCode {

  /**
   * @var string
   * @access public
   */
  /**
   * Holds the web site name
   */
  public $siteName;

  /**
   * Holds the admins email address
   */
  public $adminEmail;
  /** */

  function __construct()
  {
    $this->siteName   = $GLOBALS['cfg']['siteName'];
    $this->adminEmail = $GLOBALS['cfg']['adminEmail'];
  }


  /**
   * Checks if the calling script has been GET'ed
   *
   * @return bool
   */

  public function getMethod()
  {
    if (count($_GET)) {
      return true;
    }
    return false;
  }


  /**
   * Checks if the calling script has been POST'ed to
   *
   * @return bool
   */

  public function postMethod()
  {
    if (count($_POST)) {
      return true;
    }
    return false;
  }


  /**
   * Returns $_SERVER['PATH_INFO'] as an array
   *
   * @return array
   */

  public function parsePathInfo()
  {
    if (!empty($_SERVER['PATH_INFO'])) {
      $piBits = explode('/', $_SERVER['PATH_INFO']);
      if (!empty($piBits[1])) {
	return $piBits;
      }
    }
    return false;
  }

  /**
   * Sets a message for display on the next page load
   *
   * @param string $message
   */

  public function setMessage($message)
  {
    Session::addToArray('messages', $message);
    return;
  }


  /**
   * Sets an error message for display on the next page load
   *
   * @param string $message
   */

  public function setError($message)
  {
    Session::addToArray('errors', $message);
    return;
  }

  /**
   * Redirects the user to a given url, the referring url or LINK_ROOT
   *
   * @param string $url URL to redirect too
   */

  public function redirect($url = false)
  {
    if (!$url) {
      if (!empty($_SERVER['HTTP_REFERER'])) {
	$url = $_SERVER['HTTP_REFERER'];
      }
      else {
	$url = LINK_ROOT;
      }
    }
    header('Location: '.$url);
    exit;
  }


  /**
   * Basic update method for in-place editing
   *
   * @param string $mod The 'code' for the module being updated
   * @param string $text The new text for the module
   * @return bool
   */

  public function updateByAjax($mod, $text)
  {
    if (!$GLOBALS['db']->Execute('UPDATE dynContent SET content = \''.Database::escape($text).'\', uid = '.CURRENT_UID.' WHERE dcid = \''.Database::escape($mod).'\'')) {
      if (strlen(trim($GLOBALS['db']->ErrorMsg()))) {
	trigger_error($GLOBALS['db']->ErrorMsg());
      }
      return false;
    }
    return true;
  }

  public function getDynContent($mod)
  {
    if (!$cRes = $GLOBALS['db']->GetRow('SELECT content FROM dynContent WHERE dcid = \''.Database::escape($mod).'\'')) {
      return '';
    }
    return stripslashes($cRes['content']);
  }


  /**
   * Returns page content and title by name
   *
   * @param string $name
   * @return array
   */

  public function getPageByName($name)
  {
    try {
      $page = $GLOBALS['db']->GetRow('SELECT pid, UNIX_TIMESTAMP(modDate) AS modDate, title, body, visable, inMenu FROM pages WHERE title = \''.Database::escape(urldecode($name)).'\' LIMIT 1');
    }
    catch (exception $e) {
      Tools::dump($e);
      adodb_backtrace($e->getTrace());
      return false;
    }
    if ($app = XiteCode::checkForApp($page['body'])) {
      if (XiteCode::appExists($app)) {
	$page['body'] = require APP_DIR.$app.'/init.php';
      }
      else {
	$page['body'] = 'App not found: '.$app;
      }
    }
    $page['title'] = stripslashes($page['title']);
    $page['body']  = stripslashes($page['body']);
    return $page;
  }


  /**
   * Returns all page titles that should be in the nav menu
   *
   * @return array
   */

  public function getPagesInMenu()
  {
    try {
      $pages = $GLOBALS['db']->GetAll('SELECT title FROM pages WHERE visable = \'Y\' AND inMenu = \'Y\' ORDER BY title');
    }
    catch (exception $e) {
      Tools::dump($e);
      adodb_backtrace($e->getTrace());
      return false;
    }
    foreach ($pages as $k => $page) {
      $pages[$k]['title'] = stripslashes($page['title']);
    }
    return $pages;
  }


  /**
   * Adds a page to the pages table
   *
   * @param array
   */

  public function addPage($postArray)
  {
    try {
      $GLOBALS['db']->Execute('INSERT INTO pages (title, body, visable, inMenu) VALUES (\''.Database::escape($postArray['title']).'\', \''.Database::escape($postArray['body']).'\', \''.$postArray['visable'].'\', \''.$postArray['inMenu'].'\')');
    }
    catch (exception $e) {
      Tools::dump($e);
      adodb_backtrace($e->getTrace());
      return false;
    }
    return true;
  }


  /**
   * Checks the given string for an 'app' tag.
   * If found returns the app name. Otherwise returns false
   *
   * @param string $body
   * @return mixed
   */

  private function checkForApp(& $body)
  {
    $matches = array();
    preg_match('/\[app (\w+)\]/', $body, $matches);
    if (!empty($matches[1])) {
      return $matches[1];
    }
    return false;
  }


  /**
   * Returns true if APP_DIR.'appname' class exists.
   *
   * @param string $app
   * @return bool
   */

  private function appExists($app)
  {
    return file_exists(APP_DIR.$app.'/init.php');
  }

}

?>
